import React, { Component } from 'react';
import { Table, Icon } from 'antd';
import LinkDetails from './LinkDetails';
import moment from 'moment';
const tableWidth = ['20%', '20%', '60%'];
class Link extends Component {
    constructor(props) {
        super(props);
        this.state = {
            expandedRowKeys: [],
            active: null
        }
        this.columns = [
            {
                width: '20%',
                title: (item) => {
                    const { oneRequestDuration = '' } = this.props.data || {};
                    const _time = oneRequestDuration / 5;
                    return <div className="link-title-box">
                        <div style={{ width: tableWidth[0] }}>
                            Span名称
                        </div>
                        <div style={{ width: tableWidth[1] }}>
                            服务名称
                        </div>
                        <div className="link-progress" style={{ width: tableWidth[2] }}>
                            <div> 0ms</div >
                            <div>{this.timeFormat(_time)}</div>
                            <div>{this.timeFormat(_time * 2)}</div>
                            <div>{this.timeFormat(_time * 3)}</div>
                            <div>
                                <span>{this.timeFormat(_time * 4)}</span>
                                <span>{this.timeFormat(oneRequestDuration)}</span>
                            </div>
                        </div >
                    </div>
                },
                key: 'spanName',
                render: (item) => {
                    const { data = {}, details = {}, getLinkDetails } = this.props;
                    const { oneRequestStartTime = '', oneRequestDuration = '' } = data;
                    const isType = item.spanId === this.state.active;
                    const itemStartTiem = item.startTime - oneRequestStartTime;
                    const itemEndTiem = item.endTime - oneRequestStartTime;
                    const left = itemStartTiem / oneRequestDuration * 100;
                    const width = (itemEndTiem / oneRequestDuration * 100) - left;
                    return <div className="link-box">
                        <div style={{ width: tableWidth[0], borderBottomWidth: isType ? 1 : 0 }}>
                            <div className="link-item-name">
                                {this.getIcon(item)}
                                <i className="legend" style={{ background: this.getColor(item.errorcode), height: isType ? '96.7%' : '50%', left: (item.hierarchy * 10) + 35 }}></i>
                                <span onClick={() => { this.setActiveId(item.spanId) }}>{item.spanName}</span>
                            </div>
                        </div>
                        <div style={{ width: tableWidth[1], borderBottomWidth: isType ? 1 : 0 }}>
                            {item.service}
                        </div>
                        <div style={{ width: tableWidth[2] }}>
                            <div className="progress-bar">
                                <i style={{ width: `${width}%`, left: `${left}%`, background: this.getColor(item.errorcode) }}>
                                    <span className={(left > 10) ? 'progress-bar-start-time' : ''}>{this.timeFormat(itemStartTiem) || '0s'}</span>
                                    <span className={(width + left < 90) ? 'progress-bar-end-time' : ''}>{this.timeFormat(itemEndTiem)}</span>
                                </i>
                            </div>
                            {isType && <LinkDetails data={{ spanId: item.spanId, itemStartTiem, itemEndTiem }} details={details} getLinkDetails={getLinkDetails} timeFormat={this.timeFormat} />}
                        </div>
                    </div>
                }
            }
        ];
    }

    timeFormat(timestamp) {
        var mistiming = Math.round(timestamp / 1000);
        var formatArray = ['Year', 'Month', 'week', 'day', 'h', 'min', 's'];
        var timeArray = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
        for (var i = 0; i < timeArray.length; i++) {
            var inm = mistiming / timeArray[i];
            if (Math.floor(inm) != 0) {
                return inm.toFixed(2) + formatArray[i];
            }
        }
    }

    // 整理调用链路数据
    getDataSource = (data = [], hierarchy) => {
        const { logDetailLists = [] } = this.props.data || {};
        return data.map(item => {
            let _item = { ...item, key: item.spanId, hierarchy };
            const childData = logDetailLists.filter(items => items.parentspanId === item.spanId);
            if (childData.length > 0) {
                _item.children = this.getDataSource(childData, hierarchy + 1)
            }
            return _item;
        })
    }

    updateExpandedRowKeys = (type: string, id: string) => {
        const { expandedRowKeys = [] } = this.state || {};
        let newData = [...expandedRowKeys];
        const isThereare = expandedRowKeys.includes(id);
        if (type == 'on' && isThereare == false) {
            newData.push(id);
        } else if (type == 'off' && isThereare == true) {
            newData = newData.filter(item => item !== id);
        } else {
            return false;
        }
        this.setState({
            expandedRowKeys: newData
        })
    }

    getIcon = (props = {}) => {
        const { expandedRowKeys = [] } = this.state;
        const { spanId = '', children = [], hierarchy = 0 } = props;
        if (children.length > 0) {
            if (expandedRowKeys.includes(spanId)) {
                return <Icon style={{ marginTop: 3, marginLeft: (hierarchy * 10) }} onClick={() => { this.updateExpandedRowKeys('off', spanId) }} type="caret-down" />
            } else {
                return <Icon style={{ marginTop: 3, marginLeft: (hierarchy * 10) }} onClick={() => { this.updateExpandedRowKeys('on', spanId) }} type="caret-right" />
            }
        } else {
            return <Icon style={{ marginTop: 3, marginLeft: (hierarchy * 10), opacity: 0 }} type="caret-right" />
        }
    }

    getColor = (val) => val == 1 ? '#f42624' : val == 2 ? '#9fd80c' : val == 3 ? '#f39429' : '#eee';

    setActiveId = (id) => {
        this.setState((state) => {
            return { active: state.active == id ? null : id }
        })
    }

    render() {
        const { active = '', expandedRowKeys = [] } = this.state;
        const { data = {} } = this.props;
        const { serverNumber = '', spanIdNumber = '', oneRequestStartTime = '', oneRequestDuration = '', logDetailLists = [] } = data;
        const findRoot = logDetailLists.filter ? logDetailLists.filter(item => !item.parentspanId) : [];
        const _dataSource = findRoot.length !== 0 ? this.getDataSource(findRoot, 1) : [];
        return (
            <div className="call-link">
                <h3 className="call-link-title">调用链路</h3>
                <div className="call-link-legend">
                    <div>
                        <div>正常</div>
                        <div>非自身语法错误</div>
                        <div>自身错误</div>
                    </div>
                    <div >
                        <div>
                            <div><span>开始时间：</span>{moment(oneRequestStartTime * 1).format('YYYY-MM-DD HH:mm:ss')}</div>
                            <div><span>持续时间：</span>{this.timeFormat(oneRequestDuration)}</div>
                        </div>
                        <div>
                            <div><span>服务：</span>{serverNumber}个</div>
                            <div><span>span：</span>{spanIdNumber}个</div>
                        </div>
                    </div>
                </div>
                <div className="call-link-table">
                    <Table
                        dataSource={_dataSource}
                        columns={this.columns}
                        bordered
                        expandedRowKeys={expandedRowKeys}
                        expandIcon={() => <div style={{ opacity: 0 }}></div>}
                        pagination={false}
                        rowClassName={(record, index) => record.spanId == active ? 'rowClassActive' : 'rowClassDefault'}
                    />
                    <div className="call-link-auxiliary-line" style={{ width: tableWidth[2] }}>
                        <i></i>
                        <i></i>
                        <i></i>
                        <i></i>
                    </div>
                </div>
            </div>
        );
    }
}

export default Link;